package com.bidevalution.controller.task;

import com.bidevalution.business.service.BeSectionParamsService;
import com.bidevalution.business.service.FileCompareService;
import com.bidevalution.dao.entity.FileCompareResult;
import com.bidevalution.support.compare.FileHandler;
import com.bidevalution.support.compare.Model;
import com.bidevalution.support.util.FileTypeConvertUtil;
import com.bidevalution.support.util.FileUtil;
import com.qtp.core.util.DateUtil;
import com.qtp.core.util.IdsUtil;
import lombok.extern.log4j.Log4j2;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * Created by glodon on 2019-08-29.
 */
@Log4j2
@Component
public class FileCompareTask {

    @Value("${download.file.path}")
    private String downloadFilePath;
    @Autowired
    private FileCompareService fileCompareService;
    @Autowired
    private BeSectionParamsService beSectionParamsService;

    private Logger log = Logger.getLogger(getClass());

    /**
     * 3分钟执行一次
     *
     * @throws Exception
     */
   // @Scheduled(cron = "0 */10 *  * * * ")
    public void fileCompare() {
        try {
            //获取内网地址
            String innerFileServiceUrl = beSectionParamsService.getOneSysParamValue("INNER_FILE_UPLOAD_URL_PARAM");
            List<Map<String, String>> sectionList = fileCompareService.getCompareSections();
            if (sectionList == null || sectionList.size() == 0) {
                return;
            }
            for (Map<String, String> sectionMap : sectionList) {
                if(sectionMap == null) {
                    continue;
                }
                List<Map<String, String>> list = fileCompareService.getCompareEnterprise(sectionMap.get("sectionId"), sectionMap.get("methodId"));
                if (list != null && list.size() > 0) {
                    String inputPath, inputPath1, inputPath2;
                    String dir = "temp/filecompare/";
                    for (Map<String, String> map : list) {
                        FileUtil.downloadFile(innerFileServiceUrl + "/UploadedFile/", map.get("pdfId"), dir + map.get("pdfId") + ".pdf");
                        inputPath = dir + map.get("pdfId") + ".txt";
                        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(inputPath), "UTF-8"));
                        FileTypeConvertUtil.readPdf(writer, dir + map.get("pdfId") + ".pdf");
                    }
                    FileCompareResult fileCompareResult = null;
                    for (int i = 0; i < list.size() - 1; i++) {
                        for (int j = i + 1; j < list.size(); j++) {
                            Map<String, String> map1 = list.get(i);
                            Map<String, String> map2 = list.get(j);
                            inputPath1 = dir + map1.get("pdfId") + ".txt";
                            inputPath2 = dir + map2.get("pdfId") + ".txt";
                            FileHandler fh = new FileHandler();
                            List<String> docList1 = fh.putFileToList(inputPath1);
                            List<String> docList2 = fh.putFileToList(inputPath2);

                            Model model = new Model();
                            double avgSimilar = 0.0;
                            if (docList1.size() > docList2.size()) {
                                avgSimilar = model.getAvgSimilar(docList1, docList2);
                            } else {
                                avgSimilar = model.getAvgSimilar(docList2, docList1);
                            }
                            fileCompareResult = new FileCompareResult();
                            fileCompareResult.setSeqId(IdsUtil.uuid());
                            fileCompareResult.setSectionId(map1.get("sectionId"));
                            fileCompareResult.setEnterpriseId1(map1.get("enterpriseId"));
                            fileCompareResult.setEnterpriseName1(map1.get("enterpriseName"));
                            fileCompareResult.setFileId1(map1.get("pdfId"));
                            fileCompareResult.setEnterpriseId2(map2.get("enterpriseId"));
                            fileCompareResult.setEnterpriseName2(map2.get("enterpriseName"));
                            fileCompareResult.setFileId2(map2.get("pdfId"));
                            fileCompareResult.setSimilar((float) avgSimilar);
                            fileCompareResult.setEvalContentType(map1.get("methodId"));
                            fileCompareResult.setCreateTime(DateUtil.now());
                            fileCompareResult.setUpdateTime(DateUtil.now());
                            fileCompareService.saveSimilarEnterprise(fileCompareResult);
                        }
                    }
                    removeDir(new File(dir));
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 删除临时文件夹下内容
     * @param dir 文件目录
     */
    private static void removeDir(File dir) {
        File[] files=dir.listFiles();
        if(files != null){
            for(File file:files){
                if(file.isDirectory()){
                    removeDir(file);
                }else{
                    file.delete();
                }
            }
        }
    }

}
